/*
 * @Author:
 * @Date: 2022-11-24 13:56:00
 * @LastEditors:
 * @LastEditTime: 2022-12-23 17:55:33
 * @FilePath: \immoka-admin\src\utils\ossProvider.js
 * @Description:
 *
 * Copyright (c) 2022 by  , All Rights Reserved.
 */
import {message} from 'antd';
import {obsSts} from '@/services/commonOssSts';

import OSS_DIRS from '@/constantPool/OSS_DIRS';

type ossData = {
  oss_key: string;
  oss_secret: string;
  oss_bucket: string;
  oss_endpoint: string;
  oss_url: string;
};

class ObsProvider {
  __obsIns: Record<any, any> = {};
  __obsConfig: any = {
    oss_key: '',
    oss_secret: '',
    oss_bucket: '',
    oss_endpoint: '',
    oss_url: '',
  };

  async getObsIns() {
    // debugger
    if (this.__obsIns.bucket) return this.__obsIns;
    const ossData = await this.getEffectiveIns();
    this.__obsConfig = ossData;
    if (ossData) {
      const {oss_key, oss_secret, oss_endpoint} = ossData;
      this.__obsIns = new ObsClient({
        access_key_id: oss_key,
        secret_access_key: oss_secret,
        server: oss_endpoint,
        timeout: 60 * 5,
      });
    } else {
      throw ReferenceError('无法正确获取obs对象引用！');
    }
    return this.__obsIns;
  }

  async getEffectiveIns(): Promise<ossData | void> {
    try {
      const {
        data: {oss_key, oss_secret, oss_bucket, oss_endpoint, oss_url},
      } = await obsSts();
      return {
        oss_key,
        oss_secret,
        oss_bucket,
        oss_endpoint,
        oss_url,
      };
    } catch (e) {
      return void message.warn('获取 obs 信息失败~');
    }
  }

  async upload(file: File, dir: OSS_DIRS) {
    const OBSIns = await this.getObsIns();
    let time = new Date().getTime();
    let type = file.type.split('/')[1];
    try {
      const result = await OBSIns.putObject({
        Bucket: this.__obsConfig.oss_bucket,
        Key: dir + '/' + time + '.' + type,
        SourceFile: file,
      });
      if (result.CommonMsg.Status < 300) {
        return Promise.resolve(
          `${this.__obsConfig.oss_url}/${dir}/${time + '.' + type}`,
        );
      }
    } catch (e) {
      return Promise.reject(e);
    }
  }
}

export default ObsProvider;
